<?php

/**
 * Aurorum - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Aurorum
 * @package Aurorum
 */

/**
 * Contains global functions you can call from anywhere.
 *
 * @package Aurorum
 */

function ads_debug($var){
    ADS_Debug::dump($var);
}

function ads_get_template_zones($template) {
    if (!is_file(get_template_directory() . '/descriptor.php')) {
        throw new ADS_FileNotFoundException("Template descriptor does not exist.");
    }
    
    require(get_template_directory() . '/descriptor.php');

    if (!isset($ads_templateDescriptor)) {
        throw new ADS_TemplateDescriptorNotFoundException(
            "Template descriptor does not contain valid descriptor."
        );
    }
    if($template == 'default')
        $template = 'page.php';
    
    return isset($ads_templateDescriptor['templates'][$template]['zones']) ? $ads_templateDescriptor['templates'][$template]['zones'] : FALSE;
}

function ads_get_template_info($template) {
    if (!is_file(get_template_directory() . '/descriptor.php')) {
        throw new ADS_FileNotFoundException("Template descriptor does not exist.");
    }
    
    require(get_template_directory() . '/descriptor.php');

    if (!isset($ads_templateDescriptor)) {
        throw new ADS_TemplateDescriptorNotFoundException(
            "Template descriptor does not contain valid descriptor."
        );
    }
    if($template == 'default')
        $template = 'page.php';
    
    return isset($ads_templateDescriptor['templates'][$template]) ? $ads_templateDescriptor['templates'][$template] : FALSE;
}

function ads_get_template_descriptor() {
    if (!is_file(get_template_directory() . '/descriptor.php')) {
        throw new ADS_FileNotFoundException("Template descriptor does not exist.");
    }
    
    require(get_template_directory() . '/descriptor.php');
    
    if (!isset($ads_templateDescriptor)) {
        throw new ADS_TemplateDescriptorNotFoundException(
            "Template descriptor does not contain valid descriptor."
        );
    }
    
    return $ads_templateDescriptor;
}

function ads_enqueue_scripts() {
    // JavaScript
    wp_enqueue_script('jquery');
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-mouse');
    wp_enqueue_script('jquery-ui-widget');
    wp_enqueue_script('jquery-ui-datepicker', WP_PLUGIN_URL . '/ads-server/public/js/jquery-ui-datepicker.js', array('jquery', 'jquery-ui-core', 'jquery-ui-mouse', 'jquery-ui-widget'));
    // CSS
    wp_enqueue_style('jquery-ui-theme', WP_PLUGIN_URL . '/ads-server/public/css/jquery-ui-datepicker.css');
    wp_enqueue_style('ads-css', WP_PLUGIN_URL . '/ads-server/public/css/global.css');
}

function ads_admin_init() {
    remove_post_type_support('post', 'comments');
    remove_post_type_support('post', 'thumbnail');
    remove_post_type_support('page', 'comments');
}

function ads_admin_footer() {
//    print('
//        <script type="text/javascript">
//        jQuery(document).ready(function(){
//            jQuery(\'.ads_datepicker\').datetimepicker({dateFormat: \'yy-mm-dd\',timeFormat: \'hh:mm:ss\'});
//        });
//        </script>
//    ');
}

function add_admin_menu_separator($position) {
    global $menu;

    $index = 0;
    foreach ($menu as $offset => $section) {
        if (substr($section[2], 0, 9) == 'separator')
            $index++;
        if ($offset >= $position) {
            $menu[$position] = array('', 'read', "separator{$index}", '', 'wp-menu-separator');
            break;
        }
    }
    ksort($menu);
}

/**
 * Function builds menu and itegrates it to WordPress menu.
 */
function ads_admin_menu() {

    //load changes
    $chModel = new ADS_ChangelogModel();
    //count records
    $cnt = (int) $chModel->setFilter(array(
                array('status = %i', 0)
            ))->countChanges();

    add_admin_menu_separator(54);
    //add link to Dashboard
    add_menu_page(
            'Vysílání', 'Vysílání', 'edit_pages', 'ads_dashboard', array('ADS_Output', 'flushOutput'), WP_PLUGIN_URL . '/ads-server/public/images/server-cast.png', 3
    );
    //add link to LayoutScheduler
    add_submenu_page(
            'ads_dashboard', 'Přehled vysílání', sprintf(
                    'Přehled vysílání <span class="update-plugins count-%d" title="Nepotvrzené změny: %d"><span class="update-count">%d</span></span>
        ', $cnt, $cnt, $cnt), 'edit_pages', 'ads_dashboard', array('ADS_Output', 'flushOutput')
    );
    //add link to LayoutScheduler
    add_submenu_page(
            'ads_dashboard', 'Vysílací plán', 'Vysílací plán', 'edit_pages', 'ads_slide', array('ADS_Output', 'flushOutput')
    );
    //add link to ContentFrame
    add_submenu_page(
            'ads_dashboard', 'Datové rámce', 'Datové rámce', 'edit_pages', 'ads_dataframe', array('ADS_Output', 'flushOutput')
    );
    //add link to DataSource
    add_submenu_page(
            'ads_dashboard', 'Datové zdroje', 'Datové zdroje', 'publish_posts', 'ads_datasource', array('ADS_Output', 'flushOutput')
    );
    add_submenu_page(
            'ads_dashboard', 'Přehrávače', 'Přehrávače', 'manage_options', 'ads_player', array('ADS_Output', 'flushOutput')
    );
    add_submenu_page(
            'ads_dashboard', 'Nastavení', 'Nastavení', 'manage_options', 'ads_settings', array('ADS_Output', 'flushOutput')
    );

    if (ADS_HIDE_LINKS) {
        //remove links from menu (no need to use them)
        remove_menu_page('edit-comments.php');
        remove_menu_page('link-manager.php');
        //remove_menu_page('tools.php');
        //remove_submenu_page('themes.php','widgets.php');
        //remove_submenu_page('plugins.php','plugin-install.php');
        //remove_submenu_page('plugins.php','plugin-editor.php');
        remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=category');
        //remove_submenu_page('edit.php','edit-tags.php?taxonomy=post_tag');
        remove_submenu_page('options-general.php', 'options-discussion.php');
        //remove_submenu_page('ads_dashboard','ads_dashboard');
    }
}

function ads_smarty_link($params, $smarty) {

    $target = $params['target'];
    unset($params['target']);
    $append = $params['append'];
    unset($params['append']);
    $escape = isset($params['escape']) ? $params['escape'] : true;
    unset($params['escape']);
    print ADS_Navigator::getURL($target, $params, $append, (bool) $escape);
}

function ads_get_wp_nonce($params, $smarty) {
    $target = ADS_Navigator::parseTarget($params['target']);
    print(wp_create_nonce($target['page'] . ':' . $target['action']));
}

function ads_smarty_sortlink($params, $smarty) {
    $append = $params['append'];
    unset($params['append']);
    $params['order'] = _ifset($_GET['order'] == 'asc', 'desc', 'asc');
    print ADS_Navigator::getURL('self:' . (isset($_GET['do']) ? $_GET['do'] : 'defaultAction'), $params, $append, true);
}

function ads_smarty_sortstate($params, $smarty) {
    $isOrdered = _ifset(isset($_GET['orderBy']) && $_GET['orderBy'] == $params['orderedBy'], true, false);
    print !$isOrdered ? 'sortable desc' : 'sorted ' . _ifset(isset($_GET['order']), strtolower($_GET['order']), 'asc');
}

function ads_prepare_options($tempOptions, $index1, $index2) {
    $options = array();
    foreach ($tempOptions as $key => $option) {
        if (isset($option[$index1]) && isset($option[$index2])) {
            $options[$option[$index1]] = $option[$index2];
        } else if ($index1 == 'USE_ARR_KEY' && isset($option[$index2])) {
            $options[$key] = $option[$index2];
        }
    }
    return $options;
}

function ads_checkdate($date) {
//    return preg_match('/^(([0-9][0-9])|([1-2][0-9][0-9][0-9]))\/(([1-9])|(0[1-9])|(1[0-2]))\/(([0-9])|([0-2][0-9])|(3[0-1]))$/',$date);
    return preg_match('/^(((\d{4})(-)(0[13578]|10|12)(-)(0[1-9]|[12][0-9]|3[01]))|((\d{4})(-)(0[469]|11)(-)([0][1-9]|[12][0-9]|30))|((\d{4})(-)(02)(-)(0[1-9]|1[0-9]|2[0-8]))|(([02468][048]00)(-)(02)(-)(29))|(([13579][26]00)(-)(02)(-)(29))|(([0-9][0-9][0][48])(-)(02)(-)(29))|(([0-9][0-9][2468][048])(-)(02)(-)(29))|(([0-9][0-9][13579][26])(-)(02)(-)(29)))(\s([0-1][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9]))?$/', $date);
}

function ads_prepare_sorting($orderBy, $order, $allowedColumns) {
    return _ifset(
                    //allowed columns
                    in_array($orderBy, $allowedColumns),
                    //ok
                    array($orderBy => $order),
                    //not ok
                    array()
    );
}

function ads_prepare_paging($page, $limit, $cntRecords) {
    //validate parameters
    if (!is_int($page) || !is_int($limit) || !is_int($cntRecords)) {
        throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.', __METHOD__));
    }
    $rest = $cntRecords - ($page - 1) * $limit;

    $pager['cntRecords'] = $cntRecords;
    $pager['cntPages'] = ceil($cntRecords / $limit);
    $pager['page'] = $page;
    $pager['limit'] = $limit;
    $pager['start'] = ($page - 1) * $limit + 1;
    $pager['stop'] = ($page - 1) * $limit + (($rest >= $limit) ? $limit : $rest);
    $pager['prev'] = _ifset($page - 1 > 0, $page - 1, 1);
    $pager['next'] = _ifset($page + 1 <= $pager['cntPages'], $page + 1, $pager['cntPages']);

    return $pager;
}

function _ifset($condition, $value, $default) {
    //validate parameters
    if (!is_bool($condition)) {
        throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.', __METHOD__));
    }
    return $condition ? $value : $default;
}

function custom_login() {
    echo '<link rel="stylesheet" type="text/css" href="' . plugins_url() . '/ads-server/public/css/custom_login.css" />';
}

add_action('login_head', 'custom_login');
